//
//  NetworkTools.swift
//  FWSinaWeibo
//
//  Created by 范伟 on 16/2/25.
//  Copyright © 2016年 FanWei. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    //MARK:应用程序信息
    let appkey = "2153682552"
    let appSecret = "763cdb6c6b97b19b34965184cea829e4"
    let redirectUri = "http://www.finnciti.com"
    
    ///单例
    static let shareTools: NetworkTools = { () -> NetworkTools in
        let tools = NetworkTools(baseURL: nil)
        // 设置反序列化支持数据格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    /// 封装 AFN 方法发起网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调(json字典)
    func request(method: RequestMethod,
        urlString: String,
        parameters: [String: AnyObject]?,
        finished: (result: [String: AnyObject]?) -> ()) {
            
            let success = { (dataTask: NSURLSessionDataTask, responseObject: AnyObject?) -> () in
                if let result = responseObject as? [String: AnyObject] {
                    finished(result: result)
                } else {
                    print("数据格式错误")
                    finished(result: nil)
                }
            }
            
            let failure = { (dataTask: NSURLSessionDataTask?, error: NSError) -> () in
                print("网络请求错误\(error)")
                finished(result: nil)
            }
            
            if method == .GET {
                GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            } else {
                POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            }
    }
}
